//
//  PrayViewController.m
//  Azkar
//
//  Created by 王易 on 2018/8/26.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "PrayViewController.h"
#import "AzkarModel.h"
#import "PrayDetailView.h"
#import "CommentsCell.h"
#import "CommentsView.h"
#import "ReplyView.h"

/**
 单个祈福详情页
 */
@interface PrayViewController ()<UITableViewDelegate, UITableViewDataSource, RefreshDelegate,UIGestureRecognizerDelegate>

@property (nonatomic, strong) NSMutableArray *dataModel;

@property (nonatomic,weak) RefreshTableView *tableView;

@property (nonatomic, assign) NSInteger pageIndex;

@property (nonatomic) BOOL isRefresh;

@property (nonatomic,strong) CommentsView *commentsView;



@end

@implementation PrayViewController
- (NSMutableArray *)dataModel
{
    if (!_dataModel) {
        _dataModel = [NSMutableArray array];
    }
    return _dataModel;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [MyDimeScale setUITemplateSize:CGSizeMake(375, 667)];
    if ([[LanguageManager defaultManager].appLanguage isEqualToString:@"ar"]) {
        [MyBaseLayout setIsRTL:YES];
    }
    [self initUI];
    [self initNavigation];
    WeakSelf
    [[[NSNotificationCenter defaultCenter]rac_addObserverForName:ReplyComments_Const object:nil]subscribeNext:^(id x) {
        StrongSelf
        [self.tableView reloadData];
    }];
    __weak typeof(self) weakSelf = self;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithActionBlock:^(id  _Nonnull sender) {
        [[IQKeyboardManager sharedManager] resignFirstResponder];
        [weakSelf.commentsView hideTools];
    }];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        
        return NO;
    }else if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableView"]) {
        
        
        return NO;
    }
    else if ([NSStringFromClass([touch.view class]) isEqualToString:@"MyRelativeLayout"]) {
        if ([touch.view.superview.superview.className isEqualToString:@"UITableViewCellContentView"]) {
            return NO;
        }
        
        return YES;
    }
    else if ([NSStringFromClass([touch.view class]) isEqualToString:@"MyLinearLayout"]) {
        if ([touch.view.superview.className isEqualToString:@"UITableViewCellContentView"]) {
            return NO;
        }
        
        return YES;
    }
    return YES;
}

- (void)initUI
{
    
    MyRelativeLayout *rootLayout = [MyRelativeLayout new];
    rootLayout.myBottom = [PhoneUtil tabbarAdjustHeight];
    rootLayout.myTop = [PhoneUtil topAdjustHeightWithNavi:YES];
    rootLayout.myHorzMargin= 0;
    rootLayout.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:rootLayout];
    
    NSString *lang_type = self.blessModel.lang_type;
    if (self.publicModel.lang_type) {
        lang_type = self.publicModel.lang_type;
    }
    
    CommentsView *commentsView = [CommentsView new];
    self.commentsView = commentsView;
    commentsView.lang_type = lang_type;
    [commentsView initContentUI];
    WeakSelf
    commentsView.sendBLock = ^(UITextField *input){
        StrongSelf
        NSString *Id ;
        NSString *url;
        if (self.blessModel) {
            Id = self.blessModel.ID;
            url = [NSString stringWithFormat:@"%@/%@/comments",BlessBlog,Id];
        }else{
            Id = self.publicModel.ID;
            url = [NSString stringWithFormat:@"%@/%@/comments",PublicBless,Id];
        }
        if (!Id) {
            [AlertTools showMessage:TLString(@"error")];
            return;
        }
        
        [AlertTools showLoading];
        [[AzkarApi postData:url withParm:@{@"content":input.text,@"comment_type":@"1"}]subscribeNext:^(id x) {
            [AlertTools hideLoading];
            input.text = nil;
            self.tableView.isRefreshing = YES;
            self.blessModel.cnt_comment = [NSString stringWithFormat:@"%ld",self.blessModel.cnt_comment.integerValue+1];
        } error:^(NSError *error) {
//            [AlertTools hideLoading];
        }];
    };
    [rootLayout addSubview:commentsView];
    
    RefreshTableView *tableView = [[RefreshTableView alloc]initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.myHorzMargin = 0;
    tableView.backgroundColor = Color(@"#F7F7F7");
    tableView.myTop = 0;
    tableView.bottomPos.equalTo(commentsView.topPos);
    tableView.estimatedRowHeight = 44;
    
    tableView.estimatedSectionFooterHeight = 0;
    
    tableView.estimatedSectionHeaderHeight = 0;
    
    tableView.backgroundColor = Color(@"#F7F7F7");
    
//    self.view.backgroundColor = Color(@"#F7F7F7");
    
    self.tableView = tableView;
    
    [rootLayout addSubview:tableView];
    
    self.tableView.dataSource = self;
    
    self.tableView.delegate = self;
    
    self.tableView.tableFooterView = [UIView new];
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.tableView.refreshDelegate = self;
    
    self.tableView.canHeaderRefresh = YES;
    
    self.tableView.canFooterRefresh = YES;
    
    self.tableView.isRefreshing = YES;
    
    
    [CommentsCell registerClassToTable:self.tableView];
    
    PrayDetailView *detailView = [PrayDetailView linearLayoutWithOrientation:MyOrientation_Vert];
    detailView.frame = CGRectMake(0, 0, CGRectGetWidth(self.tableView.bounds), 0);
    [detailView initWithUI];
    detailView.blessModel = self.blessModel;
    detailView.publicModel = self.publicModel;
    
    [detailView layoutIfNeeded];
    
    self.tableView.tableHeaderView = detailView;
    
    UIImageView *emptyView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"no_content_img"]];
    [self.tableView addSubview:emptyView];
    emptyView.centerX = kScreenWidth/2;
    emptyView.top = detailView.height +60;
    emptyView.hidden = YES;
    emptyView.tag = 1024;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        emptyView.top = detailView.height +60;
        emptyView.hidden = YES;
    });

}
- (void)initNavigation{
    [self.navigationController setNavigationBarHidden:YES];
    
    [self initLeftBackNaviButton];
    
    [self.myNavigationBar.rightButton1 setImage:[UIImage RTL_ImageWithName:@"more_btn"] forState:UIControlStateNormal];
    __weak typeof(self) weakSelf = self;
    [self.myNavigationBar.rightButton1 setHyb_onTouchUp:^(UIButton *sender) {
        NSString *lang_type = weakSelf.blessModel.lang_type;
        BOOL isPublic = NO;
        NSString *Id = weakSelf.blessModel.ID;
        if (weakSelf.publicModel) {
            lang_type = weakSelf.publicModel.lang_type;
            isPublic = YES;
            Id = weakSelf.publicModel.ID;
        }
        
        ShareView *shareView = [ShareView new];
        shareView.lang_type = lang_type;
        shareView.isPublic = isPublic;
        shareView.Id = Id;
        shareView.pbModel = weakSelf.publicModel;
        shareView.model = weakSelf.blessModel;
        [shareView showView];
    }];
}

- (void)loadData
{
    
    NSString *Id ;
    NSString *url;
    UIImageView *emptyView = [self.tableView viewWithTag:1024];
    if (self.blessModel) {
        Id = self.blessModel.ID;
       url = [NSString stringWithFormat:@"%@/%@/comments",BlessBlog,Id];
        [AzkarApi readBless:Id success:^(id response) {
            PrayDetailView *detailView = (PrayDetailView*)self.tableView.tableHeaderView;
            self.blessModel.cnt_read = [response[@"cnt_read"] integerValue];
            detailView.blessModel = self.blessModel;
            emptyView.top = detailView.height+60;
        }];
    }else{
        Id = self.publicModel.ID;
        url = [NSString stringWithFormat:@"%@/%@/comments",PublicBless,Id];
        [AzkarApi readPBBless:Id success:^(id response) {
            
            self.publicModel.cnt_read = [response[@"cnt_read"] integerValue];
            PrayDetailView *detailView = (PrayDetailView*)self.tableView.tableHeaderView;
            self.publicModel.cnt_read = [response[@"cnt_read"] integerValue];
            detailView.publicModel = self.publicModel;
            emptyView.top = detailView.height+60;
        }];
    }
    if (self.bless_id) {
        Id = self.bless_id.stringValue;
        url = [NSString stringWithFormat:@"%@/%@/comments",BlessBlog,Id];
    }
    if (!Id) {
        self.tableView.isRefreshing = NO;
        return;
    }
    
    if (!self.blessModel && !self.publicModel) {
        
        NSString *url2 = [NSString stringWithFormat:@"%@/%@",BlessBlog,Id];
        [[AzkarApi getData:url2 withParm:@{@"bless_blog_id":Id}] subscribeNext:^(id x) {
            
            
            BlessModel *model = [BlessModel yy_modelWithDictionary:x];
            self.blessModel = model;
            PrayDetailView *detailView = (PrayDetailView*)self.tableView.tableHeaderView;
            detailView.blessModel = self.blessModel;
            [detailView layoutIfNeeded];
            emptyView.top = detailView.height+60;
            self.tableView.tableHeaderView = detailView;
            self.isRefresh = NO;
            [AzkarApi readBless:Id success:^(id response) {
                detailView.blessModel.cnt_read = [response[@"cnt_read"] integerValue];
            }];
        } error:^(NSError *error) {
            self.isRefresh = NO;
//            self.tableView.isRefreshing = NO;
//            self.tableView.isLoadingMoreData = NO;
        }];
    }

    [[AzkarApi getData:url withParm:@{@"limit":@"10",@"offset":[NSString stringWithFormat:@"%ld",self.pageIndex * 10 ]}] subscribeNext:^(id x) {
        self.tableView.isRefreshing = NO;
        self.tableView.isLoadingMoreData = NO;
        if (self.isRefresh) {
            self.isRefresh = NO;
            [self.dataModel removeAllObjects];
        }
        PrayCommentsModel *model = [PrayCommentsModel yy_modelWithDictionary:x];
        
//        [self.dataModel insertObjects:[model.comments reverseObjectEnumerator].allObjects atIndex:0];
        [self.dataModel addObjectsFromArray:model.comments];
//        [self.dataModel reverse];
        
        if (model.comments.count < 10) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            self.pageIndex ++ ;
        }
        
        [self.tableView viewWithTag:1024].hidden = self.dataModel.count;
        [self.tableView reloadData];
    } error:^(NSError *error) {
        [self.tableView viewWithTag:1024].hidden = self.dataModel.count;

        self.isRefresh = NO;
        self.tableView.isRefreshing = NO;
        self.tableView.isLoadingMoreData = NO;
    }];
    
}

- (void)onRefreshing:(id)control {
    if (self.isRefresh) {
        return;
    }
    self.pageIndex = 0;
    
    [self.tableView.mj_footer resetNoMoreData];
    self.isRefresh = YES;
//    [self.dataModel removeAllObjects];
    
    [self loadData];
}
- (void)onLoadingMoreData:(id)control {
    [self loadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataModel.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CommentsCell *cell = [tableView dequeueReusableCellWithIdentifier:[CommentsCell reuseIdentifier]];
    cell.commentsModel = self.dataModel[indexPath.row];
    WeakSelf
    cell.likeBlock = ^(CommentsModel *commentsModel) {
        StrongSelf
        
        if (!commentsModel.ID) {
            return;
        }
        [AlertTools showLoading];
        
        NSString *url;
        if (self.blessModel) {
            url = [NSString stringWithFormat:@"%@/%@/comment",BlessComment,commentsModel.ID];
        }else{
            url = [NSString stringWithFormat:@"%@/%@/comment",PublicBlessComment,commentsModel.ID];
        }
        
        if(!commentsModel.like){
        WeakSelf
        [[AzkarApi postData:url withParm:nil]subscribeNext:^(id x) {
            StrongSelf
            [AlertTools hideLoading];
            commentsModel.like = YES;
            commentsModel.cnt_like = [NSString stringWithFormat:@"%@",x];
//            [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:0];
            cell.commentsModel = commentsModel;
     
        } error:^(NSError *error) {
//            [AlertTools hideLoading];
        }];
        }else{
            WeakSelf
            [[AzkarApi deleteData:url withParm:nil]subscribeNext:^(id x) {
                StrongSelf
                [AlertTools hideLoading];
                commentsModel.like = NO;
                commentsModel.cnt_like = [NSString stringWithFormat:@"%@",x];
//                [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:0];
                cell.commentsModel = commentsModel;

            } error:^(NSError *error) {
//                [AlertTools hideLoading];
            }];
            
        }
    };
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *lang_type = self.blessModel.lang_type;
    if (self.publicModel.lang_type) {
        lang_type = self.publicModel.lang_type;
    }
    ReplyView *replyV = [ReplyView new];
    if (self.blessModel) {
        replyV.Id = self.blessModel.ID;
    }else{
        replyV.Id = self.publicModel.ID;
    }
    replyV.isPublic = self.publicModel ? YES : NO;
    replyV.lang_type = lang_type;
    replyV.commentsModel = self.dataModel[indexPath.row];
    [replyV showView];
}

@end
